/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.jms;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.jms.JMSException;

/**
   This class snapshots the properties that are contained within a JMS
   message.

   @author Shrideep Pallickara
   $Revision$
   $Date$
*/
 
public class JmsProperties implements JmsDebugFlags{
  
  /** The hashtable that will be holding the message properties */
  Hashtable propertiesTable;
  
  /** A list of reserved keywords that are not allowed */
  private static final String[] reservedKeywords = 
  {"if", "and", "not", "or", "true", "false"};
  
  /** This is the list of selectors that we allow, and these shouldn't be
      used in property names. Leads to parsing issues */
  private static final String[] selectorList = {"!", "|", "&", "+",   
						">", "<", "=", ",", "*"};
  
  public JmsProperties() {
    propertiesTable = new Hashtable();
  }
  
  public  void clearProperties() throws JMSException {
    propertiesTable.clear();
  }
  
  public boolean propertyExists(String name) throws JMSException {
    if (name == null) {
      throw new JMSException("Trying to query a NULL property's existence");
    }
    if (propertiesTable.containsKey(name))
      return true;

    return false;
  }
  
 
  public boolean getBooleanProperty(String name) throws JMSException {
    processPropertyName(name);
    return JmsPropertyConversionTable.getBooleanValue(retrieveProperty(name));
  }
  
  public  void  setBooleanProperty(String name, boolean value) 
    throws JMSException {
    processPropertyName(name);
    propertiesTable.put(name, new Boolean(value));
  }

  public byte getByteProperty(String name) throws JMSException {
    processPropertyName(name);
    return JmsPropertyConversionTable.getByteValue(retrieveProperty(name));
  }
  
  public void setByteProperty(String name, byte value) throws JMSException {
    processPropertyName(name);
    propertiesTable.put(name, new Byte(value));
  }
  
  public short getShortProperty(String name) throws JMSException {
    processPropertyName(name);
    return JmsPropertyConversionTable.getShortValue(retrieveProperty(name));
  }
  
  public void setShortProperty(String name, short value) throws JMSException {
    processPropertyName(name);
    propertiesTable.put(name, new Short(value));
  }

  public int getIntProperty(String name) throws JMSException {
    processPropertyName(name);
    return JmsPropertyConversionTable.getIntValue(retrieveProperty(name));
  }
  
  public void setIntProperty(String name, int value) throws JMSException {
    processPropertyName(name);
    propertiesTable.put(name, new Integer(value));
  }
  
  public long getLongProperty(String name) throws JMSException {
    processPropertyName(name);
    return JmsPropertyConversionTable.getLongValue(retrieveProperty(name));
  }
  
  public void setLongProperty(String name, long value) throws JMSException {
    processPropertyName(name);
    propertiesTable.put(name, new Long(value));
    if (JmsProperties_Debug)
      System.out.println("Set Long Property " + name + "=" + value); 
  }
  
  public float getFloatProperty(String name) throws JMSException {
    processPropertyName(name);
    return JmsPropertyConversionTable.getFloatValue(retrieveProperty(name));
  }
  
  public void setFloatProperty(String name, float value) throws JMSException {
    processPropertyName(name);
    propertiesTable.put(name, new Float(value));
    if (JmsProperties_Debug)
      System.out.println("Set Float Property " + name + "=" + value);
  }
  
  
  public double getDoubleProperty(String name) throws JMSException {
    processPropertyName(name);
    return JmsPropertyConversionTable.getDoubleValue(retrieveProperty(name));
  }
  
  public void  setDoubleProperty(String name, double value) 
    throws JMSException {
    processPropertyName(name);
    propertiesTable.put(name, new Double(value));
    if (JmsProperties_Debug)
      System.out.println("Set Double Property " + name + "=" + value);
  }
  
  
  public String getStringProperty(String name) throws JMSException {
    processPropertyName(name);
    Object propertyObj = retrieveProperty(name);
    if (propertyObj == null)
      return null;
    return JmsPropertyConversionTable.getStringValue(propertyObj);
  }
  
  public void setStringProperty(String name,String value) throws JMSException{
    processPropertyName(name);
    if (value == null) {
      value = "Supposed to be null";
    }
    propertiesTable.put(name, value);
    if (JmsProperties_Debug)
      System.out.println("Set String Property " + name + "=" + value);
  }
  
  public Object getObjectProperty(String name) throws JMSException {
    return retrieveProperty(name);
  }
  
  public void setObjectProperty(String name, Object value)
    throws JMSException {
    processPropertyName(name);
    if (value == null) {
      value = "Supposed to be null";
    }
    propertiesTable.put(name, value);
  }
  
  private void processPropertyName(String name) throws JMSException {
    /** Trim whitespace from the property name */
    name.trim();
    String exceptionInfo = "The specified property name (" + name + ") ";
    if (name == null) 
      throw new JMSException(exceptionInfo + "is null");
    if (name.length() == 0)
      throw new JMSException(exceptionInfo + "is of length zero");
    /** Test to see if it is a reserved key word */
    for (int i=0; i < reservedKeywords.length; i++) {
      if (name.equals(reservedKeywords[i])) {
	throw new JMSException(exceptionInfo + "is a reserved key in the " +
			       " selector list");
      }/*if*/
    }/*for*/	  
    
    /** Lets get the first charachter in the property string */
    String firstChar = name.substring(0,1);
    for (int i=0; i < selectorList.length; i++) {
      if (firstChar.equals(selectorList[i])) {
	throw new JMSException(exceptionInfo + "starts with (" + firstChar +
			       ") a reserved key in the selector list");
      }/*if*/
    }/*for*/
    
  }
  
  private Object retrieveProperty(String name) throws JMSException {
    //if (!propertyExists(name)) 
    //  throw new JMSException("The property (" + name +") does not exist");
    
    Object propertyValue = propertiesTable.get(name);
    if (propertyValue == null)
      return null;
    //if (propertyValue == null)
    //  throw new JMSException("The property (" + name +") maps to NULL");
    if (propertyValue.equals("Supposed to be null"))
      return null;
    return propertyValue;
  }
  
  public Enumeration getPropertyNames() throws JMSException {
    if (propertiesTable == null)
      throw new JMSException("Error in the Properties Table ");
    /** enumeration of property names */
    //return Collections.enumeration(propertiesTable.keySet());

    return propertiesTable.keys(); /** enumeration of property names */
  }
  
  /** If there is a failure in the serialization process. The value that
      is returned is NULL */
  public byte[] getBytes() {
    ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream dout;
    byte[] propertiesBytes = null;
    try {
      dout = new ObjectOutputStream(baOutputStream);
      dout.writeObject((Object)propertiesTable);

      dout.flush();
      propertiesBytes = baOutputStream.toByteArray();
    } catch (IOException ioe) {
      System.out.println("JmsProperties: Marshalling Exception " + ioe);
    } /*end try-catch block*/
    return propertiesBytes;
  }
  
  public JmsProperties(byte[] propertiesBytes) {
    ByteArrayInputStream baInputStream = 
      new ByteArrayInputStream(propertiesBytes);
    
    try {
      ObjectInputStream din = new ObjectInputStream(baInputStream);
      propertiesTable = (Hashtable)din.readObject();
      
      if (propertiesTable == null) {
	System.out.println("\n" + "The properties table in JmsProperties " + 
			   "is NULL" + "\n");
      }
    } catch (IOException ioe) {
      System.out.println("JmsProperties: Unmarshalling exception " + ioe);
    } catch (ClassNotFoundException cnfE) {
      System.out.println("JmsProperties: Unmarshalling exception " + cnfE); 
    }/*end try-catch block*/
  }

  public String toString() {
    String stringRep = "JmsProperties >>" + propertiesTable.toString();
    return stringRep;
  }

  public static void main(String[] args) {
    JmsProperties jmsProp = new JmsProperties();
    
    try {
      jmsProp.setStringProperty("Test", "Property Value being tested");
      jmsProp.setObjectProperty("TestOnObject", null);
      jmsProp.setStringProperty("sharedlet","");
      
      byte[] propBytes = jmsProp.getBytes();
      
      JmsProperties prop = new JmsProperties(propBytes);
      System.out.println(prop.getStringProperty("Test"));
      System.out.println(prop.getObjectProperty("TestOnObject"));
      System.out.println(prop.getStringProperty("sharedlet"));
      System.out.println(prop.getObjectProperty("junkProp"));
      System.out.println(prop);
    } catch (JMSException jmsEx) {
      System.out.println(jmsEx);
    }
  }


}
